package com.dongbao.core.rules.java;

import com.dongbao.core.base.CodeRulesCommonBase;
import com.dongbao.core.rules.CodeRulesBase;
import com.dongbao.entity.AwardedInfo;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PsiClassImpl;
import com.intellij.psi.impl.source.tree.PsiCommentImpl;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.tree.IElementType;
import org.jsoup.internal.StringUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 方法体内的代码行数建议不超过120行? 超过建议召开会议
 * */
public class CodeLineNumberMaxRules extends CodeRulesCommonBase implements CodeRulesBase {

    private List<String> mustAnno = Arrays.asList("param","return","author","date");

    public CodeLineNumberMaxRules(VirtualFile afterFile, PsiFile psiFile, Project project) {
        super(afterFile,psiFile,project);
        this.code = "C001";
        this.level = "C";
    }

    /**
     * 执行规则判断
     * */
    @Override
    public void run(List<AwardedInfo> deduction) {
        /* 执行分析当前class是否负责当前规则 */
        PsiAnnotation[] annotations = psiClassImpls.get(0).getModifierList().getAnnotations();
        for(PsiClassImpl psiClass:psiClassImpls){
            /* 获取所有方法 */
            PsiMethod[] allMethods = psiClass.getMethods();
            /* 读取方法上的注释检查所有方法的注释是否符合要求 */
            for(PsiMethod method:allMethods){
                Document document = PsiDocumentManager.getInstance(psiClass.getProject()).getDocument(psiClass.getContainingFile());
                int startOffset = method.getTextRange().getStartOffset();
                int endOffset = method.getTextRange().getEndOffset();
                int startLineNumber = document.getLineNumber(startOffset);
                int endLineNumber = document.getLineNumber(endOffset);
                if((endLineNumber - startLineNumber)>120){
                    /* 获取错误代码行位置 */
                    int lineNumber = document.getLineNumber(method.getTextOffset());

                    /* 方法上的注解缺少指定tag标签 */
                    packDeduction(
                            deduction,
                            psiClass.getName(),
                            psiPackageStatements.get(0).getPackageName(),
                            method.getName(),
                            "方法体内的代码行数建议不超过120行? 超过建议召开会议",
                            lineNumber,lineNumber);
                }
            }
        }
    }

    @Override
    public String describe() {
        return "设计模式与解耦";
    }
}
